package org.sang.controller.user;

import com.github.pagehelper.Page;
import org.sang.bean.User;
import org.sang.bean.UserDto;
import org.sang.common.UserUtils;
import org.sang.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userInfo")
public class UserContorller {

    @Autowired
    UserService userService;

    @PostMapping(value = "/user", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity add(@RequestBody User user) {
        return ResponseEntity.ok(userService.add(user));
    }

    @DeleteMapping(value = "/user/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity delete(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/user/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity findOne(@PathVariable Long id) {
        UserDto userDto = new UserDto();
        User user = userService.findOne(id);
        BeanUtils.copyProperties(user,userDto);
        return ResponseEntity.ok(userDto);
    }

    @GetMapping(value = "/user/info", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity findByName() {
        User u = UserUtils.getCurrentUser();
        User userinfo = (User) userService.loadUserByUsername(u.getUsername());
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userinfo,userDto);
        return ResponseEntity.ok(userDto);
    }

    @PutMapping(value = "/user/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity update(@RequestBody User user, @PathVariable Long id) {
        return ResponseEntity.ok(userService.update(user, id));
    }

    @PostMapping(value = "/user/list", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> getMemebrListByPage(
        @RequestBody User user, @RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        Page<User> page = userService.getUserListByPage(pageNum, pageSize, user);
        List<UserDto> reuslt = page.getResult().stream().map(item -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item,userDto);
            return userDto;
        }).collect(Collectors.toList());
        result.put("result", reuslt);
        result.put("total", page.getTotal());
        return ResponseEntity.ok(result);
    }


}
